package cn.com.huzo.service.trade.impl;

import cn.com.huzo.model.entities.trade.ShippingOrderLinesEntity;
import huzofw.service.impl.GenericManagerImpl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import cn.com.huzo.repository.trade.ShippingOrderLinesRepository;
import cn.com.huzo.service.trade.ShippingOrderLinesManager;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import huzofw.model.entities.paginator.Paginator;
import org.apache.commons.collections4.MapUtils;
import org.springframework.transaction.annotation.Transactional;

/**
 * 发货发令单明细管理服务对象类实现。
 *
 * @author 吴旭
 */
@Service("ShippingOrderLinesManager")
public class ShippingOrderLinesManagerImpl extends GenericManagerImpl<ShippingOrderLinesEntity, String>
        implements ShippingOrderLinesManager {

    @Resource(name = "ShippingOrderLinesRepository")
    private ShippingOrderLinesRepository _dao_lines;

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> fetchByHeaderId(Long headerId) throws Exception {
        Map<String, Object> _result = new HashMap();
        _result.put("LinesList", _dao_lines.fetchByHeaderId(headerId));

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> fetchForPage(Map<String, Object> criterion) throws Exception {
        Map<String, Object> _result = new HashMap();

        Long offset = (long) ((Integer) criterion.get("Limit")) * (((Integer) criterion.get("PageIndex")) - 1);
        long total = _dao_lines.fetchForCount(criterion);

        if (total > 0) {
            if (offset >= total) {
                offset = (total - MapUtils.getInteger(criterion, "Limit")) < 0 ? 0 : (total - MapUtils.getInteger(criterion, "Limit"));
            }
            criterion.put("Offset", offset);
            List<ShippingOrderLinesEntity> itemList = _dao_lines.fetchForPage(criterion);
            Paginator<ShippingOrderLinesEntity> paginator = new Paginator<>(itemList, offset, MapUtils.getInteger(criterion, "Limit"), total);

            _result.put("TotalRecordCount", paginator.getTotal());
            _result.put("TotalPages", paginator.getTotalPages());
            _result.put("PageIndex", paginator.getPageIndex());
            _result.put("DataList", paginator.getItemList());
            _result.put("Success", true);
        } else {
            _result.put("Success", false);
        }

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> save(Map<String, Object> criterion) throws Exception {
        Map<String, Object> _result = new HashMap();
        int _rowsAffected1 = 0;
        int _rowsAffected2 = 0;

        ObjectMapper mapper = new ObjectMapper();
        List<ShippingOrderLinesEntity> insertList = mapper.convertValue(MapUtils.getObject(criterion, "insertList"), new TypeReference<List<ShippingOrderLinesEntity>>() {
        });
        List<ShippingOrderLinesEntity> updateList = mapper.convertValue(MapUtils.getObject(criterion, "updateList"), new TypeReference<List<ShippingOrderLinesEntity>>() {
        });

        if (!insertList.isEmpty()) {
            _rowsAffected1 = _dao_lines.batchInsert(insertList);
        }
        if (!updateList.isEmpty()) {
            _rowsAffected2 = _dao_lines.batchUpdate(updateList);
        }
        /*
        if (_rowsAffected1 > 0) {
            // 审计日志
            writeAuditLog(_updatedBy, "贸易信息→发货单明细", "单据号：" + _billNo, "增加明细");
        }
        if (_rowsAffected2 > 0) {
            // 审计日志
            writeAuditLog(_updatedBy, "贸易信息→发货单明细", "单据号：" + _billNo, "更新明细");
        }*/

        if ((_rowsAffected1 + _rowsAffected2) > 0) {
            _result.put("Success", true);
            criterion.remove("insertList");
            criterion.remove("updateList");
            _result.put("LinesList", fetchForPage(criterion));
        } else {
            _result.put("Success", false);
        }

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> delete(Map<String, Object> criterion) throws Exception {
        Map<String, Object> _result = new HashMap();

        // step1: 删除引入的发货单明细
        Integer rowsAffected = _dao_lines.delete(MapUtils.getString(criterion, "LinesId"));

        if (rowsAffected > 0) {
            _result.put("Success", true);
            _result.put("LinesList", fetchForPage(criterion));
            // 审计日志
            //writeAuditLog(MapUtils.getLong(criterion, "DeletedBy"),
            //        "贸易信息→发货单明细", "明细数据（" + MapUtils.getString(criterion, "LinesData") + "）",
            //        "删除明细");
        } else {
            _result.put("Success", false);
        }

        return _result;
    }
}
